package com.baibei.product.trade;

import android.content.Context;
import android.util.Log;
import android.util.SparseArray;

import com.baibei.basic.BasicPresenterImpl;
import com.baibei.ebec.quotation.AppQuotationFilter;
import com.baibei.ebec.quotation.QuotationManager;
import com.baibei.ebec.sdk.ApiFactory;
import com.baibei.ebec.sdk.IQuotationApi;
import com.baibei.ebec.sdk.ITradeApi;
import com.baibei.ebec.sdk.IUserApi;
import com.baibei.model.BalanceInfo;
import com.baibei.model.BaseHttpResponse;
import com.baibei.model.CouponInfo;
import com.baibei.model.HeloInfo;
import com.baibei.model.HelpContentInfo;
import com.baibei.model.MarketStatusInfo;
import com.baibei.model.ProductInfo;
import com.baibei.model.QuotationInfo;
import com.baibei.model.SuggestNumbersInfo;
import com.baibei.model.TradeTimeInfo;
import com.baibei.quotation.QuotationFilter;
import com.baibei.sdk.ApiDefaultObserver;
import com.blankj.utilcode.utils.LogUtils;
import com.rae.swift.Rx;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;

/**
 * 订购页面
 * Created by ChenRui on 2017/8/8 0008 16:52.
 */
public class TradeHomePresenterImpl extends BasicPresenterImpl<TradeHomeContract.View> implements TradeHomeContract.Presenter {

    private IQuotationApi mQuotationApi;
    private ITradeApi mTradeApi;
    private IUserApi mUserApi;
    private BalanceInfo mBalanceInfo;
    private List<CouponInfo> mCouponInfos;
    private List<Integer> mSuggestNumbers;
    private int mMaxCount;

    public TradeHomePresenterImpl(Context context, TradeHomeContract.View view) {
        super(context, view);
        mQuotationApi = ApiFactory.getInstance().getQuotationApi();
        mUserApi = ApiFactory.getInstance().getUserApi();
        mTradeApi = ApiFactory.getInstance().getTradeApi();
        mCouponInfos = new ArrayList<>();
        mSuggestNumbers = new ArrayList<>();
    }


    @Subscribe
    public void onEvent(MarketStatusInfo statusInfo) {
        LogUtils.e("开休市推送", "by" + mView);
        if (mView != null) {
            mView.onLoadTradeTimeInfo(new TradeTimeInfo(statusInfo.getStatus()));
        }
    }

    @Subscribe
    public void onEvent(SparseArray<QuotationInfo> quotations) {
        // 刷新列表
        if (mView == null) {
            return;
        }
        QuotationInfo quotationInfo = quotations.get(Rx.parseInt(mView.getProduct().getProductId()));
        //更新高低价
        if (quotationInfo != null && mView != null) {
            LogUtils.e("tag推送最新价格", quotationInfo.getLast());
            mView.upDateProductPrice(quotationInfo);
        }
    }

    @Override
    public void destroy() {
        QuotationManager.getInstance().unregister(this);
        super.destroy();
    }


    @Override
    public boolean checkBalance() {
        return mBalanceInfo != null && mBalanceInfo.getBalance() <= 0;
    }

    @Override
    public void loadBalanceAndCoupons() {
        createObservable(mTradeApi.getSuggestNumbers())
                .flatMap(new Function<SuggestNumbersInfo, Observable<List<CouponInfo>>>() {
                    @Override
                    public Observable<List<CouponInfo>> apply(@NonNull SuggestNumbersInfo suggestNumbersInfo) throws Exception {
                        //加载建议数量
                        mSuggestNumbers.clear();
                        String[] numberArray = suggestNumbersInfo.getNumbers().split(",");
                        for (int i = 0; i < numberArray.length; i++) {
                            mSuggestNumbers.add(i, Rx.parseInt(numberArray[i]));
                        }
                        mMaxCount = suggestNumbersInfo.getMaxNumber();
                        return createObservable(mTradeApi.getValidCouponList(mView.getProduct().getProductId()));
                    }
                })
                .flatMap(new Function<List<CouponInfo>, Observable<BalanceInfo>>() {
                    @Override
                    public Observable<BalanceInfo> apply(@NonNull List<CouponInfo> couponInfos) throws Exception {
                        //获取体验券
                        mCouponInfos.clear();
                        mCouponInfos.addAll(couponInfos);
                        mView.onLoadCoupons(couponInfos);
                        return createObservable(mUserApi.getBalanceInfo());
                    }
                })
                .subscribe(new ApiDefaultObserver<BalanceInfo>() {
                    @Override
                    protected void onError(String s) {

                    }

                    @Override
                    protected void accept(BalanceInfo balanceInfo) {
                        //获取余额
                        mBalanceInfo = balanceInfo;
                    }
                });
    }

    @Override
    public void loadBasicData() {
        ProductInfo product = mView == null ? null : mView.getProduct();
        if (product == null) {
            return;
        }
        createObservable(mQuotationApi.getProductPrice(product.getProductId()))
                .flatMap(new Function<QuotationInfo, Observable<TradeTimeInfo>>() {
                    @Override
                    public Observable<TradeTimeInfo> apply(QuotationInfo quotationInfo) throws Exception {
                        if (mView != null) {
                            LogUtils.e("tag接口最新价格", quotationInfo.getLast());
                            mView.onLoadProductPrice(quotationInfo);
                        }
                        return createObservable(mQuotationApi.getTradeTimeInfo());
                    }
                })
                .subscribe(new ApiDefaultObserver<TradeTimeInfo>() {
                    @Override
                    protected void onError(String s) {
                    }

                    @Override
                    protected void accept(TradeTimeInfo info) {
                        if (mView != null) {
                            mView.onLoadTradeTimeInfo(info);
                        }
                        //添加开休市推送,行情推送
                        QuotationFilter filter = new QuotationFilter(AppQuotationFilter.ACTION_MARKET_STATUS);
                        filter.addAction(QuotationFilter.ACTION_QUOTATION_PRODUCT);
                        QuotationManager.getInstance().unregister(this);
                        QuotationManager.getInstance().register(TradeHomePresenterImpl.this, filter);
                    }
                });
    }

    /**
     * 获取可用的体验券
     *
     * @return return
     */
    public List<CouponInfo> getValidCouponList() {
        return mCouponInfos;
    }

    @Override
    public List<Integer> getSuggestNumbers() {
        return mSuggestNumbers;
    }

    @Override
    public int getMaxDefindCount() {
        return mMaxCount;
    }

    @Override
    public void getHelp() {
        createObservable(mTradeApi.getHelp())
                .subscribe(new ApiDefaultObserver<List<HelpContentInfo>>() {
                    @Override
                    protected void onError(String s) {

                    }

                    @Override
                    protected void accept(List<HelpContentInfo> heloInfo) {
                        mView.onLoadHelpSuccess(heloInfo.get(0).getText());
                    }
                });
    }
}
